package com.invengo.module_robot.ui.fragment.search;

import static android.widget.AbsListView.OnScrollListener.SCROLL_STATE_IDLE;
import static androidx.viewpager2.widget.ViewPager2.SCROLL_STATE_DRAGGING;

import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Switch;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.invengo.library_orionstar.RobotConstant;
import com.invengo.library_orionstar.RobotManager;
import com.invengo.library_orionstar.SpeechEvent;
import com.invengo.module_robot.BR;
import com.invengo.module_robot.R;
import com.invengo.module_robot.data.entity.ConfigBean;
import com.invengo.module_robot.databinding.FragmentSearchBinding;
import com.invengo.module_robot.ui.fragment.weiget.LinearTopSmoothScroller;

import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.utils.MaterialDialogUtils;

public class SearchFragment extends BaseFragment<FragmentSearchBinding, SearchViewModel> {
    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_search;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    /**
     * 初始化数据
     */
    @Override
    public void initData() {
        RobotManager.getInstance().changeTip(RobotConstant.TIP_SEARCH);
        RobotManager.getInstance().setSearch(true);
        new Handler().postDelayed(() -> {
//            viewModel.getPopularBeans();
            Messenger.getDefault().send(SpeechEvent.answer("请说出你要找的图书"), "SPEECH_TO_PAGE");
        }, 600);
    }


    /**
     * 论销毁观
     */
    @Override
    public void onDestroyView() {
        RobotManager.getInstance().setSearch(false);
        binding.speechView.unRegister();
        super.onDestroyView();
    }

    /**
     * 滚动项目到顶部
     * 指定item并置顶
     *
     * @param position item索引
     */
    public void scrollItemToTop(int position) {
        LinearTopSmoothScroller smoothScroller = new LinearTopSmoothScroller(getContext(), false);
        smoothScroller.setTargetPosition(position);
        binding.recyclerView.getLayoutManager().startSmoothScroll(smoothScroller);
    }


    /**
     * 初始视图可观察
     */
    @Override
    public void initViewObservable() {
        viewModel.ui.moveEvent.observe(this, integer -> scrollItemToTop(integer));
        viewModel.ui.itemEvent.observe(this, bean -> {
            Bundle bundle = new Bundle();
            bundle.putString("publisher", bean.getPublisher() + "");
            bundle.putString("author", bean.getAuthor() + "");
            bundle.putString("bookName", bean.getBookName() + "");
            bundle.putString("isbn", bean.getIsbn() + "");
            bundle.putString("image", bean.getImage() + "");
            bundle.putString("content", bean.getRemark() + "");
            NavHostFragment.findNavController(this).navigate(R.id.action_searchFragment_to_bookInfoFragment, bundle);
        });

        binding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == SCROLL_STATE_IDLE || newState == SCROLL_STATE_DRAGGING) {
                    // DES: 找出当前可视Item位置
                    RecyclerView.LayoutManager layoutManager = binding.recyclerView.getLayoutManager();
                    if (layoutManager instanceof GridLayoutManager) {
                        LinearLayoutManager manager = (GridLayoutManager) layoutManager;
                        int mFirstVisiblePosition = manager.findFirstVisibleItemPosition();
                        viewModel.setCurrentPosition(mFirstVisiblePosition);
                    }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                viewModel.setMove2Buttom(!recyclerView.canScrollVertically(2));
            }
        });
        viewModel.ui.userConfigEvent.observe(this, config -> {
            if (configDialog == null)
                initConfigDialog();
            setConfig(config);
            if (!configDialog.isShowing())
                configDialog.show();
        });
    }

    private void setConfig(ConfigBean bean) {
        if (bean != null) {
            robotHost.setText(bean.getHost() + "");
            userName.setText(bean.getUserName() + "");
            passWord.setText(bean.getPassWord() + "");
            tenantId.setText(bean.getTenantId() + "");
        }
    }

    private MaterialDialog configDialog;
    private EditText robotHost, userName, passWord,tenantId;

    /**
     * 初始化配置对话框
     */
    private void initConfigDialog() {
        configDialog = new MaterialDialog.Builder(getActivity())
                .customView(R.layout.dialog_user_config, false)
                .positiveText("确定")
                .onPositive((dialog, which) -> viewModel.saveConfig(robotHost.getText().toString().trim(), userName.getText().toString().trim(), passWord.getText().toString().trim(),tenantId.getText().toString().trim()))
                .build();
        robotHost = (EditText) configDialog.findViewById(R.id.configHost);
        userName = (EditText) configDialog.findViewById(R.id.configUserName);
        passWord = (EditText) configDialog.findViewById(R.id.configPassword);
        tenantId = (EditText) configDialog.findViewById(R.id.configTenantId);
    }
}
